package com.firmail.controller;

import com.alibaba.fastjson.JSONObject;
import com.firmail.file.service.FileOpsService;
import com.firmail.mock.center.api.IStdMockCenterServ;
import com.firmail.mock.center.api.vo.MockMetadata;
import com.firmail.mock.common.model.ReturnData;
import com.firmail.service.impl.JsonDataDisposeServImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

@RestController
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MockServerController implements IStdMockCenterServ {

    //private static final Logger LOG=  LoggerFactory.getLogger(MockServerController.class);
	
	/*public void index(){
        String shell = getPara("shell");
        ShellKit.execShell(shell);
        renderText("执行完成...");
    }


    public void runShell(){
        String shStr = getPara("shell");
        try {
            List<String> list = ShellKit.runShell(shStr);
            renderJson(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

    @Value("${scripts.dir}")
    private String scriptsDir;

    @Value("${scripts.name}")
    private String scriptsName;

    private final JsonDataDisposeServImpl jsonDataDisposeServ;

    private final FileOpsService fileOpsService;

    @Override
    public ReturnData<?> createCrossPlfMock(@RequestBody MockMetadata data) throws IOException {
        //data.setData(jsonDataDisposeServ.escapingData(data.getData()));
        return new ReturnData<>(fileOpsService.writeFile(data));
    }

    @Override
    //@SysLogger("create-mock-at-linux")
    public ReturnData<String> createMock(@RequestBody MockMetadata data) {
        //JSONObject jsonStr= JSONObject.parseObject(data);
        return new ReturnData<>(createMock(data.getRelativePath(), data.getReqMethod(), data.getDataType(), jsonDataDisposeServ.escapingData(data.getData())));
    }

    @PostMapping("create/mock-local")
    //@ResponseBody
    public String createMock(String relativePath, String reqMethod, String dataType, String data) {
        JSONObject result = new JSONObject();

        String osname = System.getProperty("os.name");
        osname = "linux";
        if ((osname != null) && (osname.toLowerCase().startsWith("win"))) {
            log.info("当前操作系统是:" + osname);
            result.put("code", "-1");
            result.put("msg", "当前服务器操作系统不是linux");
            return result.toJSONString();
        }
        log.info("接收到参数:relativePath={}, reqMethod= {}, dataType= {}, data= {}", relativePath, reqMethod, dataType, data);
        if (StringUtils.isBlank(relativePath) || StringUtils.isBlank(reqMethod)) {
            result.put("code", "-1");
            result.put("msg", "relativePath/reqMethod不能为空");
            return result.toJSONString();
        }
		
		/*String dir = DbDirConstant.findDir(dbCode);
		if(StringUtils.isBlank(dir)){
			result.put("code", "0");
	    	result.put("msg", "根据dbCode找不到对应的数据库目录");
	    	return result.toJSONString();
		}*/
        //脚本路径
        //String shellPath = request.getServletContext().getRealPath("/")+"WEB-INF/classes";
        //String cmd = shellPath + "/copyDB.sh "+ dir + " " + targetPath;
        String cmd = getRunCMD(relativePath, reqMethod, dataType, data);
        log.info("RUNCMD= {}", cmd);
        ProcessBuilder builder = new ProcessBuilder("/bin/sh", "-c", cmd);
        builder.directory(new File(scriptsDir));

        int runningStatus;
        String s;
        StringBuffer successMsg = new StringBuffer(), errInfo = new StringBuffer();
        try {
            Process p = builder.start();

            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            while ((s = stdInput.readLine()) != null) {
                log.info("shell log info ...." + s);
                successMsg.append(s);
            }
            while ((s = stdError.readLine()) != null) {
                log.error("shell log error...." + s);
                errInfo.append(s);
            }
            try {
                runningStatus = p.waitFor();
            } catch (InterruptedException e) {
                runningStatus = 1;
                log.error("等待shell脚本执行状态时，报错...", e);
                errInfo.append(e.getMessage());
            }

            closeStream(stdInput);
            closeStream(stdError);

        } catch (Exception e) {
            log.error("执行shell脚本出错...", e);
            errInfo.append(e.getMessage());
            runningStatus = 1;
        }
        log.info("runningStatus = " + runningStatus);
        if (runningStatus == 0) {
            //成功
            result.put("code", "0");
            result.put("msg", "成功" + successMsg.toString());
            return result.toJSONString();
        } else {
            result.put("code", "-1");
            result.put("msg", "执行失败： " + errInfo.toString());
            return result.toJSONString();
        }
    }


    //scriptsDir + scriptsName + ScriptsDir + " " + targetPath;
    private String getRunCMD(String relativePath, String reqMethod, String dataType, String data) {
        StringBuilder directive = new StringBuilder(scriptsDir + scriptsName);
        //StringBuilder directive= new StringBuilder("/opt/fc/" + "ops_file.sh");
        return directive.append(" ").append(relativePath).
                append(" ").append(reqMethod).
                append(" ").append(dataType).
                append(" ").append(data).
                toString();

    }

    private void closeStream(BufferedReader reader) {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (Exception e) {
            reader = null;
        }
    }

    public static void main(String[] args) {
        //System.out.println(getRunCMD("/ois-hr/hr/ohgf/","get","json","yutdi;"));
    }


}
